package com.cqcvc.config;

import com.cqcvc.entity.Permission;
import com.cqcvc.entity.Role;
import com.cqcvc.entity.User;
import com.cqcvc.service.PermissionService;
import com.cqcvc.service.RoleService;
import com.cqcvc.service.UserService;
import com.cqcvc.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean supports(AuthenticationToken token) {

        return token instanceof JwtToken;
    }

    /**
     * 授权访问那些url
     * @param principals
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username=(String) principals.iterator().next();
        //获取角色
        Set<String> roles=roleService.getRolesByUsername(username);
        //获取权限
        Set<String> permissions=permissionService.getPermissionByUsername(username);
        //将角色和权限添加进授权对象
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 验证登录
     * @param token
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken=(JwtToken) token;
        String jwt=(String)jwtToken.getPrincipal();
        //解析JwtToken
        Claims claims = JwtUtil.parseJWT(jwt);
        String username=claims.getId();
        User user=userService.getUserByUsername(username);
        if(user==null){
            System.out.println("登录失败!");
            return null;
        }
        return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
    }
}
